package com.fzb.fetch.mail;

import com.fzb.common.IOUtil;
import org.apache.http.Header;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

public class HttpUtil {
    private static Logger log = Logger.getLogger(HttpUtil.class);
    public static CloseableHttpClient httpClient = HttpClients.createDefault();

    public static Map<String, Object> postContentType(String urlPath, Map<String, String[]> params, ResponseData<?> responseData, Map<String, String> reqHeaders, String filePath)
            throws IOException, InstantiationException {
        log.info(urlPath + " http post params " + params);
        return connectType(postForm(urlPath, params), responseData, filePath);
    }

    public static Map<String, Object> postContentType(String urlPath, byte[] date, ResponseData<?> responseData, String filePath)
            throws IOException, InstantiationException {
        return connectType(postForm(urlPath, date), responseData, filePath);
    }

    private static HttpPost postForm(String urlPath, Map<String, String[]> params) {
        HttpPost httPost = new HttpPost(urlPath);
        List nvps = new ArrayList();
        if (params == null) {
            return httPost;
        }
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            for (String string : params.get(key)) {
                try {
                    nvps.add(new BasicNameValuePair(key, new String(URLDecoder.decode(string, "UTF-8"))));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            httPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return httPost;
    }

    private static HttpPost postForm(String urlPath, byte[] data) {
        HttpPost httpost = new HttpPost(urlPath);
        httpost.setEntity(new ByteArrayEntity(data));
        return httpost;
    }

    public static Map<String, Object> connectType(HttpRequestBase httpRequestBase, ResponseData<?> responseData, String filePath)
            throws IOException, InstantiationException {
        Class<?> clazz = responseData.getClazz();
        setHttpHeaders(httpRequestBase);

        CloseableHttpResponse response = httpClient.execute(httpRequestBase);
        Map headerMap = new HashMap();
        Header[] headers = response.getAllHeaders();
        for (int t = 0; t < headers.length; t++) {
            Header header = headers[t];
            headerMap.put(header.getName(), header.getValue());
        }
        if (clazz == String.class) {
            String str = new String(IOUtil.getByteByInputStream(response.getEntity().getContent()));
            responseData.setT(str);
        }
        return headerMap;
    }

    public static Map<String, Object> getContentType(String urlPath, ResponseData<?> responseData, String filePath)
            throws IOException, InstantiationException {
        HttpGet httpGet = new HttpGet(urlPath);
        return connectType(httpGet, responseData, filePath);
    }

    private static void setHttpHeaders(HttpRequestBase header) {
        header.setHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0");
        header.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        header.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        header.setHeader("Accept-Encoding", "gzip, deflate");
        header.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        header.setHeader("Connection", "keep-alive");
    }
}
